package com.XDApp.xdbase.activitys;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.utils.ACache;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.UpdateUserState;
import com.XDApp.xdbase.utils.UpdateUserState.IUpdateUserState;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CircleImageView;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;

public class MySettingActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "MySettingActivity";
	private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private SharedPreferences sp;
	private RelativeLayout rl_setNickname, rl_setpwd, rl_setphone;
	private TextView tv_right, tv_title, username, name, tv_phone;
	private ImageView iv_back;

	private CircleImageView headicon;
	private PopupWindow mpopupWindow;
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private File tempFile;
	private Bitmap bitmap;
	private ACache mCache;
	private boolean isChange = false;

	private String phone;
	private String nickName;
	private String userID;
	private String pwd;
	private String userLogo;

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_mysetting);
		sp = getSharedPreferences(MainActivity.class.getSimpleName(), MODE_PRIVATE);
		rl_setNickname = (RelativeLayout) findViewById(R.id.rl_setnickname);
		rl_setpwd = (RelativeLayout) findViewById(R.id.rl_setpwd);
//		rl_setsex = (RelativeLayout) findViewById(R.id.rl_setsex);
		rl_setphone = (RelativeLayout) findViewById(R.id.rl_setphone);

		username = (TextView) findViewById(R.id.tv_username);
		name = (TextView) findViewById(R.id.tv_name);
		tv_phone = (TextView) findViewById(R.id.tv_phone);
		tv_right = (TextView) findViewById(R.id.title_right);
		tv_title = (TextView) findViewById(R.id.title_text);
		iv_back = (ImageView) findViewById(R.id.title_back);
		headicon = (CircleImageView) findViewById(R.id.iv_icon);

		rl_setNickname.setOnClickListener(this);
		rl_setpwd.setOnClickListener(this);
//		rl_setsex.setOnClickListener(this);
		rl_setphone.setOnClickListener(this);
		headicon.setOnClickListener(this);

		iv_back.setOnClickListener(this);
		UpdateUserState.add(iUpdateUserState);
	}

	IUpdateUserState iUpdateUserState = new IUpdateUserState() {

		@Override
		public void update(Intent data) {
			finish();
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		UpdateUserState.remove(iUpdateUserState);
	}

	@Override
	protected void initEvents() {
		isChange = sp.getBoolean(MainActivity.class.getSimpleName(), false);
		mCache = ACache.get(this);
		tv_title.setText("个人设置");
		tv_right.setVisibility(View.GONE);
		phone = getIntent().getStringExtra("phone");
		nickName = getIntent().getStringExtra("nickName");
		userID = getIntent().getStringExtra("userID");
		pwd = getIntent().getStringExtra("nickName");
		userLogo = getIntent().getStringExtra("userLogo");

		username.setText(nickName);
		name.setText(nickName);
		tv_phone.setText(phone);
		if (isChange) {
			bitmap = mCache.getAsBitmap("xslBitmap");
			headicon.setImageBitmap(bitmap);
		} else {
			if (TextUtils.isEmpty(userLogo)) {
				headicon.setBackgroundResource(R.drawable.set_headicon);
			} else {
				Picasso.with(mContext).load(userLogo).placeholder(R.drawable.set_headicon).into(headicon);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_setnickname:// 修改昵称
			Intent intent1 = new Intent(mContext, ChangeNickNameActivity.class);
			intent1.putExtra("userID", userID);
			startActivityForResult(intent1, 10001);
			break;
		case R.id.rl_setpwd:// 修改密码
			Intent intent2 = new Intent(mContext, ChangePwdActivity.class);
			intent2.putExtra("phone", "");
			intent2.putExtra("userID", userID);
			startActivity(intent2);
			break;
//		case R.id.rl_setsex:// 修改性别
//			Intent intent3 = new Intent(mContext, MyContactActivity.class);
//			intent3.putExtra("phone", "");
//			startActivity(intent3);
//			break;
		case R.id.rl_setphone:// 修改手机
			Intent intent4 = new Intent(mContext, ChangePhoneActivity.class);
			intent4.putExtra("phone", phone);
			intent4.putExtra("userID", userID);
			startActivity(intent4);
			break;
		case R.id.iv_icon:// 修改头像
			showPopMenu();
			break;
		case R.id.title_back:// 返回
			Intent data = new Intent();
			data.putExtra("nickName", nickName);
			data.putExtra("userLogo", userLogo);
			setResult(101, data);
			finish();
			break;
		case R.id.rl_map_storage: // 从图库获取照片
			// 打开图库
			gallery(v);
			mpopupWindow.dismiss();
			break;
		case R.id.rl_camera: // 从相机获取照片
			// 打开相机
			camera(v);
			mpopupWindow.dismiss();
			break;
		case R.id.bt_cancle: // 取消

			mpopupWindow.dismiss();
			break;
		default:
			break;
		}
	}

	private void showPopMenu() {
		View view = View.inflate(mContext, R.layout.activity_add_head, null);

		RelativeLayout map_storage = (RelativeLayout) view.findViewById(R.id.rl_map_storage);
		RelativeLayout rl_camera = (RelativeLayout) view.findViewById(R.id.rl_camera);
		Button bt_cancle = (Button) view.findViewById(R.id.bt_cancle);

		map_storage.setOnClickListener(this);
		rl_camera.setOnClickListener(this);
		bt_cancle.setOnClickListener(this);

		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				mpopupWindow.dismiss();
			}
		});

		view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_in));
		LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
		ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in));

		if (mpopupWindow == null) {
			mpopupWindow = new PopupWindow(mContext);
			mpopupWindow.setWidth(LayoutParams.MATCH_PARENT);
			mpopupWindow.setHeight(LayoutParams.MATCH_PARENT);
			mpopupWindow.setBackgroundDrawable(new BitmapDrawable());

			mpopupWindow.setFocusable(true);
			mpopupWindow.setOutsideTouchable(true);
			Log.e("test", "popupWindow执行了....");
		}

		mpopupWindow.setContentView(view);
		mpopupWindow.showAtLocation(rl_setphone, Gravity.BOTTOM, 0, 0);
		mpopupWindow.update();
	}

	/*
	 * 从相册获取
	 */
	public void gallery(View view) {
		// 激活系统图库，选择一张图片
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
		startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
	}

	/*
	 * 从相机获取
	 */
	public void camera(View view) {
		// 激活相机
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		// 判断存储卡是否可以用，可用进行存储
		if (hasSdcard()) {
			tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
			// 从文件中创建uri
			Uri uri = Uri.fromFile(tempFile);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		}
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
		startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
	}

	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/*
	 * 判断sdcard是否被挂载
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (null == data) {
			return;
		}

		if (requestCode == 10001) {
			nickName = data.getStringExtra("nickName");
			username.setText(nickName);
			name.setText(nickName);
		}
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);// media/external/images/media/4739
			}

		} else if (requestCode == PHOTO_REQUEST_CAREMA) {
			// 从相机返回的数据
			if (hasSdcard()) {
				crop(Uri.fromFile(tempFile));
			} else {
				Toast.makeText(mContext, "未找到存储卡，无法存储照片！", 0).show();
			}
		} else if (requestCode == PHOTO_REQUEST_CUT) {
			// 从剪切图片返回的数据
			if (data != null) {
				bitmap = data.getParcelableExtra("data");
				headicon.setImageBitmap(bitmap);
				upload(bitmap);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void upload(Bitmap bitmap) {
		mCache.put("xslBitmap", bitmap);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		try {
			out.flush();
			out.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		byte[] buffer = out.toByteArray();

		byte[] encode = Base64.encode(buffer, Base64.DEFAULT);
		final String photo = new String(encode);
		getData(photo);

	}

	// TODO 访问网络获取数据
	private void getData(final String image) {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("image", image);
			params.put("userID", userID);
			params.put("ostype", xdConfig.ANDRODID);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.CHANGE_HEADICON, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					Log.e(TAG, content);
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					if (content.startsWith("{")) {
						return;
					}

					JSONObject obj = JSONObject.parseObject(content);
					String data1 = obj.getString("data");

					String state = obj.getString("state");
					if ("1".equals(state)) {// {"nickName":"13521870239","userID":"187","userLogo":""}
						JSONObject data2 = JSONObject.parseObject(data1);
						String fileID = data2.getString("fileID");
						String fileUrl = data2.getString("fileUrl");
						userLogo = fileUrl;
						Editor editor = sp.edit();
						editor.putBoolean("isChange", true).commit();
					} else {
						Intent data = new Intent();
						data.putExtra("loginSuccess", false);
						setResult(110, data);
						return;
					}
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Intent data = new Intent();
		data.putExtra("nickName", nickName);
		data.putExtra("userLogo", userLogo);
		setResult(101, data);
		return super.onKeyDown(keyCode, event);

	}
}
